package org.example.fileServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.example.util.Constant;

/**
 * @classname: Server
 * @description: TODO
 * @author: kaiser
 * @date: 2024/3/16 17:30
 * @version: 1.0
 */
public final class Server {
    public static void main(String[] args) throws Exception {
        init(8888);
    }

    public static void init(int port) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(Constant.NETTY_GROUP);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.RCVBUF_ALLOCATOR,new FixedRecvByteBufAllocator(1024))
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ServerInitializer());
            ChannelFuture f = b.bind(port);
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            System.out.println("启动文件服务失败！");
            e.printStackTrace();
        } finally {
            // 优雅关闭两个 EventLoopGroup 对象
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
